import fs from 'fs'
import path from 'path'

import PROJECT from '../PROJECT'

const ENV = JSON.parse(fs.readFileSync(PROJECT.BUILD.__ENV__))
const manifest = JSON.parse(fs.readFileSync(PROJECT.BUILD_CLIENT.MANIFEST_FILESMAP))
const SRC = path.relative(PROJECT.ROOT, PROJECT.SRC.ROOT)
const IMAGES = ['.jpg', 'jpeg', '.png', '.gif']
const STYLES = ['.css', '.less']

/*
* declare global variables ahead of app requirements
*/
global.ENV = ENV
global.__ssr_isomorphic_tools__ = {}
global.__ssr_isomorphic_tools__.createRequire = originRequire => {
  const newRequire = url => {
    if (
      STYLES
      .map(ext => url.lastIndexOf(ext) === url.length - ext.length && url.length > ext.length)
      .filter(bool => bool).length > 0
    ) {
      return url
    }

    if (
      IMAGES
      .map(ext => url.lastIndexOf(ext) === url.length - ext.length && url.length > ext.length)
      .filter(bool => bool).length > 0
    ) {
      const absoluteUrl = originRequire.resolve(url)
      const relativeUrl = path.relative(PROJECT.BUILD.ROOT, absoluteUrl)
      if (path.sep !== '/') { key = key.split(path.sep).join('/') } // stupid windows path using \, replace all with /
      console.log('key: ', relativeUrl)
      return (manifest[relativeUrl] || '')
    }

    return originRequire(url)
  }

  newRequire.resolve = originRequire.resolve
  newRequire.main = originRequire.main
  newRequire.cache = originRequire.cache

  return newRequire
}